import { xssValueFilter } from '@/utils/util';

const getSelfComp = binding => {
  const { parentComp } = binding.value;
  const tooltipVm = parentComp.$refs.Tooltip;
  return tooltipVm;
};

const bindFun = (el, binding) => {
  el.onmouseenter = e => {
    const self = getSelfComp(binding);
    self.parentComp = binding.value.parentComp;
    self.config = binding.value.config;
    self.setState({ tooltipOnWid: self.parentComp.widgetInstanceId });
    if (!self.checkAvaible()) {
      return;
    }

    self.vars = binding.value.vars;
    self.extVars = binding.value.extVars ? binding.value.extVars : {};
    self.setVarsFromChart();
    self.richText = xssValueFilter(self.config.html);
    self._bindDirectiveOnmouseenter(self, binding, e);
  };

  el.onmousemove = e => {
    const self = getSelfComp(binding);
    if (!self.checkAvaible()) {
      return;
    }
    self.resetPosition(e, self);
  };

  el.onmouseleave = e => {
    const self = getSelfComp(binding);
    self.setState({ tooltipOnWid: '' });
    self.hideTip();
  };
};

if (!window.visualComp.directives['visual-tooltip']) {
  window.visualComp.directives.push('visual-tooltip');
  window.xVueWeb.app.directive('visual-tooltip', {
    beforeMount: bindFun,
    updated: bindFun,
    unmounted: el => {
      el.onmouseenter = null;
      el.onmousemove = null;
      el.onmouseleave = null;
    },
  });
}
